/*
 * ledMatrix.c
 *
  *	Project 5
 *  Created on: Mar 1, 2013
 *      Engineers: George Tkachuk & Brentton Garber 
 *      Emails: 	gtkachuk@asu.edu btgarber@asu.edu
 *      CSE 325: Embedded microprocessor Systems
 *      Spring 2013
 *      
 */
#include "common.h"

// Define our global row count and color bytes
uint8 G_ROW = 0;
uint8 G_RED[8];
uint8 G_GREEN[8];

// Initialize our led matrix components
void ledmatrix_init()
{
	// Configure port QS pins 0 - 2 for the primary (QSPI) function.
	MCF_GPIO_PTHPAR &= ~(15 << 12);
	
	// Configure port TH pins 6 - 7 for the quaternary (GPIO) function
	MCF_GPIO_DDRTH |= (3 << 6);
	
	// Initialize the QSPI module to transmit bits at a maximum clock frequency of 5MHz
	qspi_init();
	
}

// Refresh the led matrix
void ledmatrix_refresh()
{
	// Write the current row to the led matrix
	ledmatrix_write_row();
	
	// Increase our current row count
	G_ROW = (G_ROW + 1) % 8;
}

// Transmit a row data packet
void ledmatrix_write_row()
{
	// Make our data packet
	uint8 data[3];
	data[0] = G_RED[G_ROW];
	data[1] = G_GREEN[G_ROW];
	data[2] = (unsigned char)~(1 << G_ROW);
	
	MCF_GPIO_PORTTH &= ~MCF_GPIO_PORTTH_PORTTH6;
	MCF_GPIO_PORTTH |= MCF_GPIO_PORTTH_PORTTH7; 
	
	// Transfer our data packet
	qspi_transfer(data);
	
	// Flush the data to the ram
	MCF_GPIO_PORTTH |= MCF_GPIO_PORTTH_PORTTH6;
	MCF_GPIO_PORTTH &= ~MCF_GPIO_PORTTH_PORTTH7; 
}

// Transfer our pattern array into red and green bytes
void ledmatrix_write(int pattern[8][8])
{
	int row, col;
	
	// Loop through each of the rows
	for(row=0; row<8;row++)
	{
		// Set our green and red bytes to 0
		G_GREEN[row] = 0x0000;
		G_RED[row] = 0x0000;
		
		// Loop through each of the columns
		for(col=0;col<8;col++)
		{
			// If the color of the dot is Red, set our bit in the Red Byte
			if(pattern[row][col] == RED)
				G_RED[row] |= 1 << col;
			
			// If the color of the dot is Green, set our bit in the Green Byte
			if(pattern[row][col] == GREEN)
				G_GREEN[row] |= 1 << col;
			
			// If the color of the dot is Red, set our bit in both the Red and Green Bytes
			if(pattern[row][col] == ORANGE) {
				G_RED[row] |= 1 << col;
				G_GREEN[row] |= 1 << col;
			}
		}
	}
}


